package com.itheima.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

//切面
@Aspect
//被扫描
@Component
public class DivAdvice {
    //定义切点
    @Pointcut("execution(* com.itheima.dao.BookDao.div(..))")
    public void pt() {
    }

    //前置通知-获取参数信息打印
    @Before("pt()")
    public void before(JoinPoint point) {
        Object[] args = point.getArgs();
//        System.out.println(point.getSignature().getName());
        System.out.println("调用了除法:除法的参数为" + args[0] + "," + args[1]);
    }

    //后置通知-在方法执行之后执行
    @After("pt()")
    public void after() {
        System.out.println("除法调用完成");
    }

    //返回通知-在拿到返回结果之后执行(获取返回结果)
    //value 切点
    //returning 返回值对象obj 参数名和属性名一样
    //JoinPoint 如果出现 必须在第一个参数位置
    @AfterReturning(value = "pt()", returning = "obj")
    public void retuning(JoinPoint point, Object obj) {
        System.out.println("得到除法的计算结果为" + obj);
    }

    //异常通知 - 方法出现异常的时候调用
    //value 切点
    //thorwing 异常对象  方法参数名和t一样
    @AfterThrowing(value = "pt()", throwing = "t")
    public void throwing(Throwable t) {
        System.out.println("计算结果异常: 异常信息为: " + t.getMessage());
    }

    //环绕通知 - 前置后置返回异常
    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) {
        System.out.println("环绕前置通知");
        Object proceed = null;
        try {
//            Integer[] args = {8,2};
            proceed = pjp.proceed();//调用原方法
            System.out.println("环绕返回通知->" + proceed);
        } catch (Throwable e) {
//            e.printStackTrace();
            System.out.println("环绕异常通知->"+e.getMessage());
        }
        System.out.println("环绕后置通知");
        return 0;
    }

}
